//
//  CommonUtil.m
//  兼职页面
//
//  Created by kuiyuan liang on 2021/5/22.
//

#import "CommonUtil.h"

@implementation CommonUtil

/**
 为UILabel首部设置图片标签
 
 @param text 文本
 @param images 标签数组
 @param span 标签间距
 */
+(void)setText:(NSString *)text frontImages:(NSArray<UIImage *> *)images imageSpan:(CGFloat)span label:(UILabel *)label
{
    NSMutableAttributedString *textAttrStr = [[NSMutableAttributedString alloc] init];
    
    for (UIImage *img in images) {//遍历添加标签
        
        NSTextAttachment *attach = [[NSTextAttachment alloc] init];
        attach.image = img;
        //计算图片大小，与文字同高，按比例设置宽度
        CGFloat imgH = label.font.pointSize;
        CGFloat imgW = (img.size.width / img.size.height) * imgH;
        //计算文字padding-top ，使图片垂直居中
        CGFloat textPaddingTop = (label.font.lineHeight - label.font.pointSize) / 2;
        attach.bounds = CGRectMake(0, -textPaddingTop , imgW, imgH);
        
        NSAttributedString *imgStr = [NSAttributedString attributedStringWithAttachment:attach];
        [textAttrStr appendAttributedString:imgStr];
        //标签后添加空格
        [textAttrStr appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
    }
    
    //设置显示文本
    [textAttrStr appendAttributedString:[[NSAttributedString alloc]initWithString:text]];
    //设置间距
    if (span != 0) {
        [textAttrStr addAttribute:NSKernAttributeName value:@(span)
                            range:NSMakeRange(0, images.count * 2/*由于图片也会占用一个单位长度,所以带上空格数量，需要 *2 */)];
    }
    
    label.attributedText = textAttrStr;
}


+ (CGFloat)countHeight:(NSString *)content font:(UIFont *)font width:(CGFloat)width{
    
    
    CGFloat height = [content boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
    options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin
    attributes:@{ NSFontAttributeName : font } context:nil].size.height;
    return height;
}
+(CGFloat)countWidth:(NSString *)content font:(UIFont *)font height:(CGFloat)height{
    CGFloat w = [content boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
    options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin
    attributes:@{ NSFontAttributeName : font } context:nil].size.width;
    return w;
}

+(void)setupPlaceholderView:(UITableView *)tableView models:(NSArray *)models{
    if (models.count == 0) {
        tableView.tableFooterView = [[PlaceholderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, AD(400))];
    }else{
        tableView.tableFooterView = [UIView new];
    }
}

@end
